﻿using DTcms.Core.Common.Emum;
using DTcms.Core.Common.Helper;
using DTcms.Core.DBFactory.Database;
using DTcms.Core.IServices;
using DTcms.Core.Model.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DTcms.Core.Services
{
    /// <summary>
    /// 支付方式接口实现
    /// </summary>
    public class PaymentService : BaseService, IPaymentService
    {
        public PaymentService(IDbContextFactory contentFactory) : base(contentFactory) { }

        /// <summary>
        /// 删除支付方式(含站点支付方式删除)
        /// </summary>
        public async Task<bool> DeleteAsync(int id, WriteRoRead writeAndRead = WriteRoRead.Write)
        {
            _context = _contextFactory.CreateContext(writeAndRead);
            var model = await _context.Set<Payment>().FirstOrDefaultAsync(x => x.Id == id);
            if (model == null)
            {
                throw new ResponseException("数据不存在或已删除");
            }
            //删除站点支付方式
            var removeList = _context.Set<SitePayment>().Where(x => x.SiteId == model.Id);
            _context.Set<SitePayment>().RemoveRange(removeList);
            //删除站点
            _context.Set<Payment>().Remove(model);
            return await this.SaveAsync();
        }

        /// <summary>
        /// 批量删除(含站点支付方式删除)
        /// </summary>
        public async Task<bool> DeleteAsync(IEnumerable<int> listIds, WriteRoRead writeAndRead = WriteRoRead.Write)
        {
            _context = _contextFactory.CreateContext(writeAndRead);
            IEnumerable<Payment> list = await _context.Set<Payment>().Where(x => listIds.Contains(x.Id)).ToListAsync();
            if (list == null)
            {
                throw new ResponseException("数据不存在或已删除");
            }
            //删除站点支付方式
            foreach(var model in list)
            {
                var removeList = _context.Set<SitePayment>().Where(x => x.SiteId == model.Id);
                _context.Set<SitePayment>().RemoveRange(removeList);
            }
            //删除站点
            _context.Set<Payment>().RemoveRange(list);
            return await this.SaveAsync();
        }
    }
}
